package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import com.fsd.core.bean.Tree;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.J_board;
import com.fsd.admin.service.J_boardService;
import com.fsd.admin.dao.J_boardDao;

@Service("j_boardServiceImpl")
public class J_boardServiceImpl extends MainServiceImpl<J_board, String> implements J_boardService{

    private String depict = "论坛版块";
    
    @Resource(name = "j_boardDaoImpl")
	public void setBaseDao(J_boardDao J_boardDao) {
		super.setBaseDao(J_boardDao);
	}
	
	@Resource(name = "j_boardDaoImpl")
	private J_boardDao objectDao;

	//版块根级编码
	public static final String FSDBOARD = "FSDBOARD";
	
	/**
	 * 栏目递回创建
	 * @param object
	 * @param objList
	 */
	private void getObjectStruct(J_board object, List<J_board> objList){
		for (J_board obj : objList) {
			if(object.getId().equals(obj.getParentid())){
				object.getList().add(obj);
				if (!Boolean.valueOf(obj.getIsleaf()))
					this.getObjectStruct(obj, objList);
			}
		}
	}
	/**
	 * 获取栏目结构
	 * @param id
	 * @return
	 */
	private J_board getObjectStructByID(String id, String companyid) throws Exception{
		List<J_board> allObjectList = objectDao.queryByHql("from J_board where companyid in ('" + companyid + "','0') and deleted = '0' order by sort asc");
		Map<String, J_board> objectMap = new HashMap<String, J_board>();
		List<J_board> objectList = new ArrayList<J_board>();
		List<J_board> objList = new ArrayList<J_board>();
		for (J_board obj : allObjectList) {
			objectMap.put(obj.getId(), obj);
			if("0".equals(obj.getParentid())){
				objList.add(obj);
			}else{
				objectList.add(obj);
			}
		}
		for (J_board obj : objList) {
			this.getObjectStruct(obj, objectList);
		}
		if (objectMap != null && objectMap.containsKey(id))
			return objectMap.get(id);
		else
			return null;
	}
	
	
	private String checkLeaf(String fid){
		long num = objectDao.getCount("parentid = '"+ fid +"'", "deleted = '0'");
		if (num > 0)
			return "false";
		return "true";
	}
    
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.asc("sort"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				c.add(Restrictions.eq("parentid", objectMap.get("fid")));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 异步加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTree(String fid, A_Employee employee) throws Exception{
		J_board subject = this.getObjectStructByID(fid, employee.getCompanyid());
		List<Tree> treelist = new ArrayList<Tree>();
		if (subject != null && subject.getList() != null && subject.getList().size() > 0){
			Tree tree = null;
			J_board obj = null;
			for (Object o : subject.getList()) {
				obj = (J_board)o;
				tree = new Tree();
				tree.setId(obj.getId());
				tree.setText(obj.getTitle());
				tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
				treelist.add(tree);
			}
		}
		return treelist;
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	public void saveObject(J_board obj, A_Employee employee) throws Exception{
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
        	if (obj.getId().equals(obj.getParentid())){
    			throw new BusinessException(depict + "所属板块不得选择自己!");
        	}
            J_board old_obj = objectDao.get(obj.getId());
			String fid = old_obj.getParentid();
            old_obj.setParentid(obj.getParentid());
			old_obj.setParentname(obj.getParentname());
			old_obj.setTitle(obj.getTitle());
			old_obj.setDescription(obj.getDescription());
			old_obj.setImageurl(obj.getImageurl());
			old_obj.setIspublish(obj.getIspublish());
			old_obj.setSort(obj.getSort());
			old_obj.setRemark(obj.getRemark());
            old_obj.setUpdatedate(this.getData());//设置修改日期
			old_obj.setUpdateemployeeid(employee.getId());//设置修改用户id
			old_obj.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
            objectDao.update(old_obj);
			if (!fid.equals(obj.getParentid())){
				objectDao.executeHql("update J_board set isleaf = '" + this.checkLeaf(obj.getParentid()) + "' where id = '" + obj.getParentid() + "'");
				objectDao.executeHql("update J_board set isleaf = '" + this.checkLeaf(fid) + "' where id = '" + fid + "'");
			}
        }else{
            //添加
            obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setIsleaf("true");
			obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			objectDao.save(obj);
			objectDao.executeHql("update J_board set isleaf = 'false' where id = '" + obj.getParentid() + "'");
        }
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getTitle(), employee, J_boardServiceImpl.class);
    }
    
    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String oid = dir.get(0);
		objectDao.executeHql("update J_board set deleted = '1', updatedate = '" + this.getData() +
				"', updateemployeeid = '" + employee.getId() + "', updateemployeename = '" + employee.getRealname() +
				"' where id in (" + ids + ")");
		J_board obj = objectDao.get(oid);
		if (obj != null){
			objectDao.executeHql("update J_board set isleaf = '" + this.checkLeaf(obj.getParentid()) + "' where id = '" + obj.getParentid() + "'");
		}
		this.sysLogService.saveObject(Config.LOGTYPESC, this.depict + ids, employee, J_boardServiceImpl.class);
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public J_board getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		J_board obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		
		return obj;
	}
	
	/**
	 * 顺序排序
	 * @param parameters
	 */
	public void updateSortObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		List<String> idList = (List<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(idList);
		J_board objDW = objectDao.get(objectMap.get("id").toString());
		if (objDW == null)
			throw new BusinessException(depict + "获取定位对象为空!");
		List<J_board> objList = objectDao.queryByHql("from J_board where " +
				"parentid = '" + objDW.getParentid() + "' and deleted = '0' " +
				"and id not in (" + ids + ") " +
				"and sort >= " + objDW.getSort() + " order by sort asc");
		long sort = objDW.getSort();
		for (String id : idList) {
			objectDao.executeHql("update J_board set sort = " + sort + " where id = '" + id + "'");
			sort++;
		}
		for (J_board obj : objList) {
			objectDao.executeHql("update J_board set sort = " + sort + " where id = '" + obj.getId() + "'");
			sort++;
		}
	}
}
